/*
 * UIUtilities.java
 *
 * Created on 2004/11/18 +0900
 *
 * $Revision: 59 $
 * $Date: 2008-12-28 19:22:21 +0000 (Sun, 28 Dec 2008) $
 */

package org.gikolet.framework.ui;

import java.util.Vector;

/**
 * @author Tetsutaro (latest modification by $Author: tetsutaro.ss $)
 * @version $Revision: 59 $ $Date: 2008-12-28 19:22:21 +0000 (Sun, 28 Dec 2008) $
 */
public final class UIUtilities {

    private UIUtilities() {
    }

    // サイズを調整する
    // 位置よりもサイズ優先
    public static Dimension getPreferredSize(Widget control, int width,
	    int height) {
	Dimension d = control
		.getPreferredSize(Widget.DEFAULT_LAYOUT, Widget.DEFAULT_LAYOUT);

	int hintWidth = Widget.DEFAULT_LAYOUT;
	int hintHeight = Widget.DEFAULT_LAYOUT;
	if (d.getWidth() > width) {
	    hintWidth = width;
	}
	if (d.getHeight() > height) {
	    hintHeight = height;
	}
	if (hintWidth != Widget.DEFAULT_LAYOUT || hintHeight != Widget.DEFAULT_LAYOUT) {
	    d = control.getPreferredSize(hintWidth, hintHeight);
	}
	if (hintWidth != Widget.DEFAULT_LAYOUT) {
	    d.setWidth(Math.min(d.getWidth(), width));
	}
	if (hintHeight != Widget.DEFAULT_LAYOUT) {
	    d.setHeight(Math.min(d.getHeight(), height));
	}
	// d.setSize(Math.min(d.getWidth(), width), Math.min(d.getHeight(),
	// height));
	return d;
    }

    public static String[] split(Font font, String str, int width) {
	if (str.length() == 0) {
	    return new String[] { "" };
	}
	Vector vw = new Vector();
	StringBuffer sb = new StringBuffer();
	int x = 0;
	for (int i = 0; i < str.length(); i++) {
	    char c = str.charAt(i);
	    int cw = font.charWidth(c);

	    if (x == 0 && cw > width) {
		vw.addElement(String.valueOf(c));
		continue;
	    }
	    if (x + cw > width) {
		vw.addElement(sb.toString());
		sb.delete(0, sb.length());
		x = 0;
	    }

	    sb.append(c);
	    x += cw;
	}
	if (sb.length() > 0) {
	    vw.addElement(sb.toString());
	}
	String[] lines = new String[vw.size()];
	vw.copyInto(lines);

	return lines;
    }

    public static int getLineBreak(Font font, String str, int off, int len,
	    int width) {
	int l = 1;
	if (str.length() == 0) {
	    return off;
	}
	int w = font.charWidth(str.charAt(off));
	if (w >= width) {
	    return off + 1;
	}
	while (off + l < str.length() && l <= len) {
	    int ww = font.substringWidth(str, off, l);
	    if (ww > width) {
		l--;
		break;
	    }
	    l++;
	}
	return off + l;
    }

    public static String[] getLines(Font font, String text, int width) {
	Vector w = new Vector();
	String[] lines;
	width++;

	int s = 0;
	while (s < text.length()) {
	    int t = UIUtilities.getLineBreak(font, text, s, text.length() - s,
		    width);
	    w.addElement(text.substring(s, t));
	    s = t;
	}
	lines = new String[w.size()];
	w.copyInto(lines);
	return lines;
    }
}
